import logging
from os import path
from uuid import uuid4
import tablib
from django.conf import settings
from common.utils.decorator import check_user_vcode

_LOGGER = logging.getLogger(__name__)


def export_file(request, resp_items, key_mapper, file_name='export_data', maximum_row=20000, as_csv=None):
    check_user_vcode(request)
    filename = gen_filename(file_name, as_csv=as_csv)
    header = {item['key']: item['name'] for item in key_mapper}
    target_file, row_counter = [], 0
    for idx, item in enumerate(resp_items):
        row = []
        for key in header:
            value = round(item.get(key, '-'), 2) if isinstance(item.get(key, '-'), float) else item.get(key, '-')
            row.append(value)
        target_file.append(row)
        row_counter += 1
        if row_counter >= maximum_row:
            break
    return redirect_to_file(target_file, list(header.values()), filename, as_csv=as_csv)


def redirect_to_file(items, header, filename, as_csv=None):
    file_path = path.join(settings.EXPORT_PATH, filename)
    data = tablib.Dataset(*items, headers=header)
    f = open(file_path, 'a') if as_csv else open(file_path, 'wb')
    target = data.csv if as_csv else data.xlsx
    f.write(target)
    return {'url': '/export_data/%s' % filename}


def gen_filename(base, as_csv=None):
    qs = base + '_' + str(uuid4())
    return qs + '.csv' if as_csv else qs + '.xlsx'
